package com.youlai.mrp.service;

import cn.hutool.core.lang.Assert;
import com.youlai.mrp.query.BaseQuery;
import com.youlai.mrp.query.PageQuery;
import com.youlai.mrp.entity.MrpFccotableEntity;
import com.youlai.mrp.repository.MrpFccoTableRepository;
import com.youlai.common.base.BaseService;
import com.youlai.common.model.Option;
import com.youlai.common.result.PageResult;
import com.youlai.common.result.Result;
import com.youlai.utils.IdWorker;
import com.youlai.system.util.SecurityUtils;
import com.youlai.core.security.model.SysUserDetails;
import com.youlai.system.service.SysDictService;
import jakarta.annotation.Resource;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class MrpFccoTableService extends BaseService<MrpFccotableEntity> {
    @Autowired
    private MrpFccoTableRepository repository;

    @PersistenceContext
    private EntityManager em;

    public EntityManager getEntityManager() {
        return em;
    }

    @Resource
    SysDictService sysDictService;

    /**
     * 分页查询列表
     *
     * @param queryParams
     * @return
     */
    public PageResult<MrpFccotableEntity> getPageByHql(PageQuery queryParams) {
        String keywords = queryParams.getKeywords();
        // 动态拼接sql
        String hql = "from MrpFccotableEntity where 1=1 and deleted = 0 ";
        if (StringUtils.isNotEmpty(keywords)) {
            hql += " and (" +
                    " customerNo like '%" + keywords + "%' " +
                    " or shippingNo like '%" + keywords + "%' " +
                    ") ";
        }
        return super.getPageByHql(queryParams,hql);
    }

    public Result<MrpFccotableEntity> save(MrpFccotableEntity entity) {
        boolean isCreate = false;
        if(entity.getMrpFcCoTableId()==null) {
            isCreate = true;
            entity.setMrpFcCoTableId(IdWorker.generateId());
        }
        return super.save(entity, isCreate);
    }

    protected void beforeSave(MrpFccotableEntity  entity, Boolean isCreate){
        // 校验员工编号是否存在
        String itemNo = entity.getItemNo();
        Specification<MrpFccotableEntity> spec = (Root<MrpFccotableEntity> root, CriteriaQuery<?> cq, CriteriaBuilder cb) -> {
            Predicate predicate = cb.and(cb.equal(root.get("itemNo"), itemNo));
            predicate = cb.and(cb.equal(root.get("sourceNo"), entity.getSourceNo()),predicate);
            predicate = cb.and(cb.equal(root.get("isFinish"), 0),predicate);
            return predicate;
        };
        long count = repository.count(spec);
        Assert.isTrue(count == 0, "货号 "+itemNo+" +来源单号 "+entity.getSourceNo()+" 已存在");

        super.beforeSave(entity,isCreate);
    }

    public MrpFccotableEntity findById(Long id){
        Optional<MrpFccotableEntity> optional  = repository.findById(id);
        if(optional.isPresent()) {
            return optional.get();
        }
        return null;
    }


    public List<MrpFccotableEntity> findListBy(MrpFccotableEntity entity){
        // 动态拼接sql
        String hql = " from MrpFccotableEntity where 1=1";
        if (StringUtils.isNotEmpty(entity.getItemNo())  ) {
            hql += " and customerNo like '%" + entity.getItemNo() +"%'";
        }
        if (entity.getIsFinish()!=null  ) {
            hql += " and isFinish = " + entity.getIsFinish() +" ";
        }
        hql += " order by  originalDemandDate ";
        return super.findListBy(entity,hql);
    }

    public Boolean deleteAllById(String idStrs){
        SysUserDetails user = SecurityUtils.getUser();
        // 逻辑删除
        List<Long> ids = Arrays.asList(idStrs.split(",")).stream()
                .map(idStr -> Long.parseLong(idStr)).collect(Collectors.toList());
        for(Long id:ids) {
            Optional<MrpFccotableEntity> optional  = repository.findById(id);
            if(optional.isPresent()) {
                MrpFccotableEntity entity = optional.get();
                entity.setDeleted(1);

                entity.setUpdateBy(user.getUserId());
                entity.setUpdateName(user.getUsername());
                repository.save(entity);
            }
        }
        return true;
    }

    public List<Option> listEngEmpOptions(BaseQuery baseQuery) {
        Specification<MrpFccotableEntity> spec  = (Root<MrpFccotableEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) -> {
            Predicate predicate = cb.and(cb.equal(root.get("status"), 1));
            predicate = cb.and(cb.equal(root.get("deleted"), 0), predicate);
            return predicate;
        };
        List<MrpFccotableEntity> list = repository.findAll(spec);
        List<Option> lastList = new ArrayList<>();
        for(MrpFccotableEntity o:list) {
            Option option = new Option<String>();
            option.setLabel(o.getSourceNo());
            option.setValue(o.getItemNo());
            lastList.add(option);
        }
        return lastList;
    }
}


